import AuthAPI, { type LoginData } from "@/api/auth";
import UserAPI, { type UserInfo } from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";
import { TOKEN_KEY } from "@/enums/CacheEnum";

export const useUserStore = defineStore("user", () => {
  const user = ref<UserInfo>({
    roles: [],
    perms: [],
    userInfo: {}, // 用户信息
    isInit: true, // 是否需要加载路由
  });

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.login(loginData)
        .then((data: any) => {
          const { token } = data;
          localStorage.setItem(TOKEN_KEY, token); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          localStorage.setItem("loginInfoData", JSON.stringify(data));
          user.value.userInfo = data;
          user.value.username = data.userName;
          user.value.nickname = data.nickName;
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      UserAPI.getInfo()
        .then((data) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }
          if (!data.roles || data.roles.length <= 0) {
            reject("getUserInfo: roles must be a non-null array!");
            return;
          }
          Object.assign(user.value, { ...data });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 退出登录
  function logout() {
    return new Promise<void>((resolve, reject) => {
      localStorage.setItem(TOKEN_KEY, "");
      localStorage.removeItem("loginInfoData");
      location.reload(); // 清空路由
      resolve();
      // AuthAPI.logout()
      //   .then(() => {
      //     localStorage.setItem(TOKEN_KEY, "");
      //     location.reload(); // 清空路由
      //     resolve();
      //   })
      //   .catch((error) => {
      //     reject(error);
      //   });
    });
  }

  // remove token
  function resetToken() {
    return new Promise<void>((resolve) => {
      localStorage.setItem(TOKEN_KEY, "");
      resetRouter();
      resolve();
    });
  }
  //是否需要加载路由
  const setIsInit = (isInit: boolean) => {
    user.value.isInit = isInit;
  };
  const setUserInfo = (data: any) => {
    user.value.userInfo = data;
    user.value.username = data.userName;
    user.value.nickname = data.nickName;
  };
  return {
    user,
    login,
    getUserInfo,
    logout,
    resetToken,
    setUserInfo,
    setIsInit,
  };
});

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
  return useUserStore(store);
}
